package com.donghuayuan.kotlincar

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.text.TextUtils
import androidx.databinding.DataBindingUtil
import com.donghuayuan.kotlincar.adapter.LogoAdapter
import com.donghuayuan.kotlincar.bean.LogoBean
import com.donghuayuan.kotlincar.databinding.ActivityLogoBinding
import com.donghuayuan.kotlincar.bean.Result
import com.donghuayuan.kotlincar.net.CarApi
import com.donghuayuan.kotlincar.net.RetrofitUtils
import com.google.gson.Gson
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import retrofit2.Call
import retrofit2.Response
import java.util.*
/**
 * 携程
 * https://blog.csdn.net/HugMua/article/details/126044114
 */
class LogoActivity : AppCompatActivity() {
    //使用的时候再添加
    val binding: ActivityLogoBinding by lazy {
        DataBindingUtil.setContentView(this,R.layout.activity_logo)
    }
    private val mList = mutableListOf<Result>()
    val adapter: LogoAdapter by lazy {
        LogoAdapter(this@LogoActivity, mList)
    }
    var letter_msg = "当前品牌首字母："
    var letter = "A"
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        //设置布局中的Adapter绑定当前的Adapter，直接进行赋值
        binding.adapter = adapter
        //赋值
        binding.name = letter_msg + letter

        //挂起函数
        runBlocking{
            launch {
                loadData(letter)
            }
        }

        binding.logoBtn1.setOnClickListener {
            val lt = binding.logoEdt.text.toString().trim().uppercase()
            if (!TextUtils.isEmpty(lt) && letter!=lt) {
                letter = lt
                binding.name = letter_msg + letter
                runBlocking{
                    launch {
                        loadData(letter)
                    }
                }
            }
        }
    }

    private suspend fun loadData(letter: String) {
        //与Api关联起来
        val api = RetrofitUtils.getApi(CarApi.base_url, CarApi::class.java)
        //请求数据
        val call = api.getCarLogo(CarApi.key, letter)
        call?.enqueue(object :retrofit2.Callback<LogoBean>{
            override fun onResponse(call: Call<LogoBean>, response: Response<LogoBean>) {
                val bean = response.body()
//                var gson=Gson()
//                println("请求成功"+gson.toJson(bean))
                adapter.addDatas(bean?.result)

            }

            override fun onFailure(call: Call<LogoBean>, t: Throwable) {
                println("请求失败")
            }

        })
    }
}